/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { AbstractSyncAsyncMessageBus } from './AbstractSyncAsyncMessageBus'
import { IMessagePublication } from './IMessagePublication'
import { BusConfiguration } from '../config/BusConfiguration'
import { SyncAsyncPostCommand } from './SyncAsyncPostCommand'
import { SyncPubSub } from '../config/SyncPubSub'
import { IPublicationErrorHandler } from './error/IPublicationErrorHandler'
import { PublicationError } from './error/PublicationError'


export class MBassador<T> extends AbstractSyncAsyncMessageBus<T> {
    constructor(errorHandle?: IPublicationErrorHandler) {
        super(new BusConfiguration()
            .addFeature(SyncPubSub.Default())
            .addPublicationErrorHandler(errorHandle))
    }

    public publish(message: T): IMessagePublication {
        let pub = this.createMessagePublication(message);
        try {
            pub.execute();
        } catch (error) {
            this.handlePublicationError(new PublicationError().setCause(error).setErrorMessage("Error during publish sync of message"))
        } finally {
            return pub;
        }
    }

    public publishAsync(message: T): IMessagePublication {
        let pub = this.createMessagePublication(message);
        try {
            this.publishAsyncStart(message, pub);
        } catch (error) {
            this.handlePublicationError(new PublicationError().setCause(error).setErrorMessage("Error during publish Async of message"))
        } finally {
            return pub;
        }
    }

    public post(message: T): SyncAsyncPostCommand<T> {
        return new SyncAsyncPostCommand<T>(this, message);
    }
}